let http = require("http");
let crypto = require("crypto");
const { spawn } = require("child_process");
const sendMail = require("./sendMail");
let SECRET = "123456";
function sign(body) {
  return `sha1=` + crypto.createHmac("sha1", SECRET).update(body).digest("hex");
}
let server = http.createServer(function (req, res) {
  if (req.method === "POST" && req.url === "/webhook") {
    let buffers = [];
    req.on("data", function (buffer) {
      buffers.push(buffer);
    });
    req.on("end", function (buffer) {
      let body = Buffer.concat(buffers);
      let event = req.headers["x-github-event"];
      let signature = req.headers["x-hub-signature"];
      if (signature !== sign(body)) {
        return res.end("not allowed");
      }
      res.setHeader("Content-Type", "application/json");
      res.end(JSON.stringify({ ok: true }));
      //   开始部署
      if (event == "push") {
        let payload = JSON.parse(body);
        let child = spawn("sh", [`./${payload.repository.name}.sh`]);
        let buffers = [];
        child.stdout.on("data", function (buffer) {
          buffers.push(buffer);
        });
        child.stdout.on("end", function (buffer) {
          let logs = Buffer.concat(buffers).toString();
          console.log(logs);
          sendMail(`
                <h1>部署日期:${new Date()}</h1>
                <h2>部署人:${payload.pusher.name}</h2>
                <h2>部署邮箱:${payload.pusher.email}</h2>
                <h2>提交信息:${
                  payload.head_commit && payload.head_commit["message"]
                }</h2>
                <h2>部署日志:${logs.replace("\r\n", "<br/>")}</h2>
          `);
        });
      }
    });
  } else {
    res.end("not found");
  }
});
server.listen(4000, () => {
  console.log("http://localhost:4000");
});
